<template>
  <div class="app-container">
    <FilterSearch :value="queryParams" :config="configData" :labelCol="8" :wrapperCol="16" layout="inline">
    </FilterSearch>
    <div class="main">
      <div class="table">
        <a-table :scroll="{ x: 1500 }" bordered :dataSource="tableData.dataSource" :columns="tableData.columns"
          :loading="tableData.loading">
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="handleChange(record, 'edit')">
                编辑
              </a-button>
              <a-button type="link" @click="handleChange(record, 'remove')">
                删除
              </a-button>
              <a-button type="link" v-if="record.materialType == MATERIAL.REGISTRATION"
                @click="handleChange(record, 'printLabel')">
                打印标签
              </a-button>
              <a-button type="link" v-if="record.materialType == MATERIAL.REGISTRATION"
                @click="handleChange(record, 'printCaseNum')">
                打印盒号
              </a-button>
            </template>
            <template v-if="column.key === 'materialType'">
              <template v-for="item in typeOptions.options1">
                <span v-if="record.materialType == item.codeValue" color="#f50">{{ item.codeName }}</span>
              </template>
            </template>
            <template v-if="column.key === 'state'">
              <template v-for="item in typeOptions.options2">
                <span v-if="record.state == item.codeValue" color="#f50">{{ item.codeName }}</span>
              </template>
            </template>
            <template v-if="column.key === 'index'">
              <span>{{ (index + 1) }}</span>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal v-model:open="modalOpen.open1" style="width: 75%;" :title="modalOpen.title" :maskClosable="false"
      :closable="false">
      <div class="modal-body">
        <a-form :model="formState" ref="formRef" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
          autocomplete="off">
          <a-row>
            <a-col :span="8">
              <a-form-item label="材料类型" name="materialType" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-select allowClear v-model:value="formState.materialType">
                  <a-select-option v-for="(item, index) in typeOptions.options1" :value="item.codeValue" :key="index">
                    {{ item.codeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="formState.materialType == MATERIAL.REGISTRATION">
            <a-col :span="24">
              <a-form-item label="上传图片材料" name="fileList" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }">
                <a-upload v-model:file-list="formState.fileList" multiple @change="uploadChange" :action="getHttps"
                  :headers="getHeaders" :before-upload="beforeUpload" list-type="picture-card" @preview="onPreview">
                  <div v-if="formState.fileList.length < 8">
                    <plus-outlined />
                    <div style="margin-top: 8px">上传图片材料</div>
                  </div>
                </a-upload>
              </a-form-item>
            </a-col>
          </a-row>
          <a-col :span="8">
            <a-form-item label="合同号" name="contractNum">
              <a-input v-model:value="formState.contractNum" />
            </a-form-item>
          </a-col>
          <a-row v-show="formState.materialType == MATERIAL.REGISTRATION">
            <a-col :span="8" v-for="(item, index) in formState.carNumList" :key="index">
              <a-form-item :label="'车架号'" name="carNum">
                <a-input v-model:value="item.frameNumber" @change="carNumChange">
                  <template #addonAfter>
                    <div @click="removeCarNum(index)">
                      <DeleteOutlined></DeleteOutlined>
                    </div>
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
              <a-form-item label="">
                <a-button @click="dataBaseContractNum">
                  匹配基础数据
                </a-button>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="formState.materialType == MATERIAL.REGISTRATION">
            <a-col :span="8">
              <a-form-item label="盒号" name="caseNum">
                <a-input v-model:value="formState.caseNum" placeholder="自动生成" disabled>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="件号" name="partNum">
                <a-input v-model:value="formState.partNum" placeholder="自动生成" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="排序号" name="orderNum">
                <a-input v-model:value="formState.orderNum" placeholder="自动生成" disabled />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="formState.materialType == MATERIAL.CONTRACT">
            <a-col :span="8" v-for="(item, index) in contractList" :key="index">
              <a-form-item :label="item.label" :name="item.name" :label-col="{ span: 14 }" :wrapper-col="{ span: 10 }">
                <a-input v-model:value="item.value" @input="item.value = item.value.replace(/[^0-9]/g, '')">
                  <template #addonAfter>
                    份
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8" v-for="(item, index) in formState.reserve1" :key="index">
              <a-form-item :label="item.label" :name="item.name" :label-col="{ span: 14 }" :wrapper-col="{ span: 10 }">
                <a-input v-model:value="item.value" @input="item.value = item.value.replace(/[^0-9]/g, '')">
                  <template #addonBefore>
                    <DeleteOutlined @click="removeContract(index)" />
                  </template>
                  <template #addonAfter>
                    份
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="formState.materialType == MATERIAL.CONTRACT">
            <a-col :span="8">
              <a-form-item label="添加新文件">
                <a-input v-model:value="formState.newname">
                  <template #addonAfter>
                    <PlusOutlined @click="addContract" />
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="handleChange({}, 'material')" type="primary">保存</a-button>
          </div>
          <div class="modal-btn">
            <a-button @click="cancel('material')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>

    <a-modal v-model:open="modalOpen.open2" style="width:800px;" title="图片预览" :maskClosable="false" :closable="false">
      <div class="modal-body">
        <a-image :src="preview" :preview="false"></a-image>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="cancel('preview')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>

    <div class="shade" v-show="spin">
      <a-spin size="large" />
    </div>
  </div>
</template>
<script  lang='ts' setup>
import { computed, ref, reactive } from 'vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { insertOrder, insertMaterial, updateMaterial, deleteMaterial, getContractNum, getMaterialList, materialInfo, printMaterialLabel } from "@/api/commerExpress";
import { previewFiles, getCarNum, getQueryAll } from "@/api/common";
import { getToken, getUserId } from "@/utils/auth";
import { formatDate } from "@/utils";
import { user as useUser } from "@/store";
import { MATERIAL } from "@/utils/config";
import { useRouter } from 'vue-router';
const router = useRouter();

const user = useUser();
const queryParams = ref({
  pageNumber: 10,
  pageSize: 1,
  expressNum: "",
  signer: user.$state.userName,
  signTime: formatDate(new Date()),
  expressManageId: ''
});
const spin = ref(false);
const formRef = ref({});
const preview = ref(null);
const typeOptions = reactive({
  options1: [],
  options2: []
});
const contractList = ref([
  {
    label: "售后回租赁合同",
    value: "",
    status: false,
    props: 'afterSalesLeasebakContract'
  },
  {
    label: "抵押合同(盖章)",
    value: "",
    status: false,
    props: 'sealOfMortgageContract'
  },
  {
    label: "款项用途确认函",
    value: "",
    status: false,
    props: 'confirmationLetterForThePurposeOfFunds'
  },
  {
    label: "抵押合同(签字)",
    value: "",
    status: false,
    props: 'signatureOfMortgageContract'
  },
  {
    label: "个人信息保护政策",
    value: "",
    status: false,
    props: 'personalInformationProtectionPolicy'
  },
  {
    label: "挂靠协议",
    value: "",
    status: false,
    props: 'affiliationAgreement'
  },
  {
    label: "租赁物接收确认函及资金收据",
    value: "",
    status: false,
    props: 'leaseReceiptConfirmationAndFundReceipt'
  },
  {
    label: "付款通知书",
    value: "",
    status: false,
    props: 'paymentAdvice'
  },
  {
    label: "服务费确认函",
    value: "",
    status: false,
    props: 'serviceChargeConfirmationLetter'
  },
  {
    label: "款项代收确认函",
    value: "",
    status: false,
    props: 'paymentCollectionConfirmationLetter'
  },
  {
    label: "不可撤销确认函",
    value: "",
    status: false,
    props: 'lrrevocableConfirmationLetter'
  },
  {
    label: "业务确认函",
    value: "",
    status: false,
    props: 'businessConfirmationLetter'
  }
]);

interface FormState {
  [props: string]: string | number | Array<object>;
  carNumList: Array<any>;
  reserve1: any
}
let formState: FormState = reactive({
  materialType: MATERIAL.REGISTRATION,
  fileList: [],
  carNumList: [{}],
  reserve1: []
});
const disStatus = reactive({
  btn1: false,
  btn2: true,
  inp: false
});
const tableData = reactive({
  dataSource: [],
  columns: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      align: 'center'
    },
    {
      title: '合同号',
      dataIndex: 'contractNum',
      key: 'contractNum',
    },
    {
      title: '车架号',
      dataIndex: 'carNum',
      key: 'carNum'
    },
    {
      title: '材料类型',
      dataIndex: 'materialType',
      key: 'materialType'
    },
    {
      title: '盒号',
      dataIndex: 'caseNum',
      key: 'caseNum',
    },
    {
      title: '件号',
      dataIndex: 'partNum',
      key: 'partNum',
    },
    {
      title: '排序号',
      dataIndex: 'orderNum',
      key: 'orderNum'
    },
    {
      title: '操作',
      key: 'action',
      width: 260,
      fixed: 'right'
    },
  ],
  loading: false,
  total: 0
});
const modalOpen = reactive({
  open1: false,
  open2: false,
  index: 0,
  title: "新建材料",
  status: 0
});
const configData = computed(() => {
  let config = {
    itemConfig: [
      {
        type: "input",
        prop: "expressNum",
        allowClear: "关闭",
        label: "快递单号",
        placeholder: "请输入",
        disabled: disStatus.inp
      },
      {
        type: "input",
        prop: "signer",
        allowClear: "关闭",
        label: "签收人",
        placeholder: "",
        disabled: true
      },
      {
        type: "input",
        prop: "signTime",
        allowClear: "关闭",
        label: "签收日期",
        placeholder: "",
        disabled: true
      }
    ],
    operate: [
      {
        icon: "",
        type: "primary",
        name: "新建快递",
        handleClick: insertExprecss,
        rule: true,
        disabled: disStatus.btn1
      },
      {
        icon: "",
        type: "primary",
        name: "添加材料",
        handleClick: insert,
        rule: true,
        disabled: disStatus.btn2
      },
      {
        icon: "",
        type: "primary",
        name: "保存",
        handleClick: reload,
        rule: true,
        disabled: disStatus.btn2
      }
    ],
    rules: {

    },
  };
  return config;
});
const rules = computed(() => {
  let rules = {
    contractNum: [{ required: true, message: "请输入", trigger: "blur" }],
    carNum: [] as any
  };
  if (formState.materialType == MATERIAL.REGISTRATION) {
    rules['carNum'] = [{ required: true, message: "请输入", trigger: "blur" }]
  }
  return rules;
});
const getHttps = computed(() => {
  return import.meta.env.VITE_BASE_URL + '/resource/upload';
})
const getHeaders = computed(() => {
  return {
    zuulToken: getToken(),
    globalUserId: getUserId()
  };
});
function carNumChange() {
  if (formState.carNumList.length > 0) {
    for (let i = 0; i < formState.carNumList.length; i++) {
      if (formState.carNumList[i]['frameNumber']) {
        formState.carNum = formState.carNumList[i]['frameNumber'];
        return;
      }
    }
  }
  formState.carNum = '';
}
function beforeUpload(file: any) {
  const isPic = file.type == 'image/png' || file.type == 'image/jpg' || file.type == 'image/jpeg';
  if (!isPic) {
    message.info('请上传图片');
    return false;
  }
  return isPic;
}
function uploadChange({ fileList }: any) {
  let bool = true;
  for (const key in fileList) {
    if (fileList[key]['percent'] == 100 && fileList[key].response) {
      previewFiles({ resourceId: fileList[key].response.data }).then((res: any) => {
        if (res) {
          fileList[key].url = res;
          fileList[key].preview = res;
          fileList[key].thumbUrl = res;
        }
      })
    } else {
      bool = false;
    }
  }
  if (bool) {
    OCRIdentify();
  }
};
function onPreview(file: any) {
  preview.value = file.url;
  modalOpen.open2 = true;
}
function OCRIdentify() {
  if (formState.fileList.length <= 0) {
    formState.carNumList = [{frameNumber:""}];
    message.info("请上传");
    return false;
  }
  spin.value = true;

  let list = formState.fileList.filter((item: any) => { return item.response.data });
  let ids = list.map((item: any) => { return item.response.data });
  getCarNum({ resourceIds: ids }).then((res: any) => {
    if (res) {
      if (res.length > 0) {
        formState.carNumList = [{frameNumber:""}];
        for (const key in res) {
          if (res[key]['frameNumber']) {
            formState.carNumList.push({frameNumber:res[key].frameNumber});
          }
        }
      }
      carNumChange();
    }
    spin.value = false;
  });
}
function dataBaseContractNum() {
  if (formState.carNumList.length > 1) {
    message.info('存在多个车架号,请删除');
    return;
  }
  if (formState.carNumList.length <= 0) {
    message.info('未识别到车架号');
    return;
  }
  spin.value = true;
  getContractNum({ carNum: formState.carNumList[0].frameNumber }).then((res: any) => {
    if (res) {
      for (const key in res) {
        formState[key] = res[key];
      }
    }
    setTimeout(() => {
      spin.value = false;
    }, 500);
  })
}
function insertExprecss() {
  if (queryParams.value.expressNum) {
    insertOrder({ expressNum: queryParams.value.expressNum }).then((res: any) => {
      if (res) {
        message.success("新建快递成功");
        disStatus.btn1 = true;
        disStatus.btn2 = false;
        disStatus.inp = true;
        queryParams.value.expressManageId = res;
      }
    })
  } else {
    message.info("请输入快递单号");
    return false;
  }
}
function insert() {
  modalOpen.open1 = true;
  modalOpen.title = "新增材料";
  modalOpen.status = 0;
}
function reload() {
  router.go(0);
}
function handleChange(row: any = {}, type: string) {
  switch (type) {
    case 'material':
      formRef.value.validate().then(() => {
        let params = Object.assign(queryParams.value, formState);
        params['expressNum'] = queryParams.value.expressNum;
        params['reserve1'] = JSON.stringify(formState['reserve1']);
        if (params.fileList.length > 0) {
          params.registrationCertificatePhoto = "";
          for (const key in params.fileList as object) {
            params.registrationCertificatePhoto += params.fileList[key].response.data + ',';
          }
          params.registrationCertificatePhoto = params.registrationCertificatePhoto.slice(0, -1);
        }
        if (params.carNumList.length > 0) {
          for (let i = 0; i < params.carNumList.length; i++) {
            if (params.carNumList[i]['frameNumber']) {
              params.carNum = params.carNumList[i]['frameNumber'];
              break;
            }
          }
          params['ocrFields'] = params.carNumList.filter((item: any) => {
            return item.frameNumber == params.carNum;
          })[0];
        }
        if (params.materialType == MATERIAL.CONTRACT) {
          for (const key in contractList.value) {
            params[contractList.value[key]['props']] = contractList.value[key].value;
          }
        }
        spin.value = true;
        if (modalOpen.status == 0) {
          insertMaterial({ createMaterialCommExpressMaterialVo: params }).then((res: any) => {
            if (res) {
              message.success("新建成功");
              getLoad();
            };
            spin.value = false;
            cancel('material');
          });
        } else {
          updateMaterial(params).then((res: any) => {
            if (res) {
              message.success("编辑成功");
              getLoad();
            };
            spin.value = false;
            cancel('material');
          });
        }
      });
      break;
    case 'edit':
      spin.value = true;
      materialInfo({ id: row.id, materialType: row.materialType }).then(async (res: any) => {
        if (res) {
          formState = Object.assign(formState, res,{createdTime:"",updatedTime:""});
          for (const key in contractList.value) {
            contractList.value[key]['value'] = res[contractList.value[key]['props']];
          }
          formState['reserve1'] = res['reserve1'] ? JSON.parse(res['reserve1']) : '';
          if (formState.registrationCertificatePhoto) {
            let ids = formState.registrationCertificatePhoto.split(",");
            let fileList = [] as Array<object>;
            for (const key in ids) {
              await previewFiles({ resourceId: ids[key] }).then((res: any) => {
                if (res) {
                  fileList.push({
                    uid: res,
                    name: res,
                    url: res,
                    status: 'done',
                    preview: res,
                    thumbUrl: res,
                    response: {
                      data: ids[key],
                      status: {
                        code: 0,
                        msg: "Success"
                      }
                    }
                  });
                }
              })
            }
            formState['fileList'] = fileList;
          }
          if (formState.carNum) {
            formState.carNumList = [{ frameNumber: formState.carNum }];
          }
          modalOpen.title = "编辑材料";
          modalOpen.status = 1;
          modalOpen.open1 = true;
          spin.value = false;
        }
      });
      break;
    case 'remove':
      deleteMaterial({ id: row.id }).then((res: any) => {
        if (res) {
          message.success('删除成功');
          getLoad();
        }
      })
      break;
    case 'printLabel':
      materialInfo({ id: row.id, materialType: row.materialType }).then((res: any) => {
        if (res) {
          printMaterialLabel({ printStatus: MATERIAL.LABEL, carNum: res.carNum, partNum: res.partNum, caseNum: res.caseNum, contractNum: res.contractNum }).then((res: any) => {
            console.log(res);
          })
        }
      });
      break;
    case 'printCaseNum':
      materialInfo({ id: row.id, materialType: row.materialType }).then((res: any) => {
        if (res) {
          printMaterialLabel({ printStatus: MATERIAL.CASENUM, carNum: res.carNum, partNum: res.partNum, caseNum: res.caseNum, contractNum: res.contractNum }).then((res: any) => {
            console.log(res);
          })
        }
      });
      break;
    default:
      break;
  }
}
function getLoad() {
  if (queryParams.value.expressManageId) {
    tableData.loading = true;
    getMaterialList({ expressManageId: queryParams.value.expressManageId }).then((res: any) => {
      tableData.dataSource = res;
      tableData.total = res.length;
      tableData.loading = false;
    })
  }
}
function cancel(type: string) {
  switch (type) {
    case "material":
      modalOpen.open1 = false;
      modalOpen.title = "新增材料";
      modalOpen.status = 0;
      for (const key in formState) {
        delete formState[key];
      }
      contractList.value = [{
        label: "售后回租赁合同",
        value: "",
        status: false,
        props: 'afterSalesLeasebakContract'
      },
      {
        label: "抵押合同(盖章)",
        value: "",
        status: false,
        props: 'sealOfMortgageContract'
      },
      {
        label: "款项用途确认函",
        value: "",
        status: false,
        props: 'confirmationLetterForThePurposeOfFunds'
      },
      {
        label: "抵押合同(签字)",
        value: "",
        status: false,
        props: 'signatureOfMortgageContract'
      },
      {
        label: "个人信息保护政策",
        value: "",
        status: false,
        props: 'personalInformationProtectionPolicy'
      },
      {
        label: "挂靠协议",
        value: "",
        status: false,
        props: 'affiliationAgreement'
      },
      {
        label: "租赁物接收确认函及资金收据",
        value: "",
        status: false,
        props: 'leaseReceiptConfirmationAndFundReceipt'
      },
      {
        label: "付款通知书",
        value: "",
        status: false,
        props: 'paymentAdvice'
      },
      {
        label: "服务费确认函",
        value: "",
        status: false,
        props: 'serviceChargeConfirmationLetter'
      },
      {
        label: "款项代收确认函",
        value: "",
        status: false,
        props: 'paymentCollectionConfirmationLetter'
      },
      {
        label: "不可撤销确认函",
        value: "",
        status: false,
        props: 'lrrevocableConfirmationLetter'
      },
      {
        label: "业务确认函",
        value: "",
        status: false,
        props: 'businessConfirmationLetter'
      }];
      formState['fileList'] = [];
      formState['carNumList'] = [{}];
      formState['materialType'] = MATERIAL.REGISTRATION;
      formState['reserve1'] = [];
      break;
    case 'preview':
      modalOpen.open2 = false;
      break;
    default:
      break;
  }
}
function addContract() {
  if (formState.newname) {
    formState.reserve1.push({ label: formState.newname, value: null })
    formState.newname = "";
  } else {
    return false;
  }
}
function removeContract(index: number) {
  formState.reserve1?.splice(index, 1);
}
function removeCarNum(index: number) {
  if (formState.carNumList.length == 1) {
    return;
  }
  formState.carNumList?.splice(index, 1);
}
function getOptionsList() {
  getQueryAll({ codeType: 'materialType' }).then((res: any) => {
    typeOptions.options1 = res;
  });
  getQueryAll({ codeType: 'state' }).then((res: any) => {
    typeOptions.options2 = res;
  });
}
getLoad();
getOptionsList();
</script>
<style></style>